﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

namespace Bussines.Utils
{
    public class Utils
    {
        public static string HashMD5(string input)
        {
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }

        public static string FullApplicationPath
        {
            get
            {
                return
                    HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, "") +
                    ApplicationPath;
            }
        }

        public static string ApplicationPath
        {
            get
            {
                string url = HttpContext.Current.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                return url + "/";
            }
        }

        public static string CheckImage(string ImageUrl)
        {
            if (ImageUrl.Trim().Length <= 3) return "Hidden";
            return "";
        }

        public static bool CheckExtensionImage(string ImageName)
        {
            string strExtension = Path.GetExtension(ImageName).ToUpper();
            if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" || strExtension == ".PNG" ||
                strExtension == ".SWF")
                return true;
            return false;
        }

        //thu muc chua cac Album hinh
        public static String GetGalleryPath()
        {
            try
            {
                return PhysicalApplicationPath() + "//Gallery//";
            }
            catch
            {
                return "";
            }
        }

        public static string ImagesUrl()
        {
            try
            {
                return ApplicationPath + "Images/";
            }
            catch
            {
                return "";
            }
        }

        public static string ImagesUrlAdmin()
        {
            try
            {
                return ApplicationPath + "Admin/Images/";
            }
            catch
            {
                return "";
            }
        }

        public static string ImagesUrlWebMaster()
        {
            try
            {
                return ApplicationPath + "WebMaster/Images/";
            }
            catch
            {
                return "";
            }
        }

        public static string PhysicalApplicationPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }

        public static bool IsDate(string Text)
        {
            bool result = true;
            DateTime date;
            try
            {
                date = Convert.ToDateTime(Text);
            }
            catch
            {
                result = false;
            }
            return result;
        }

        // sinh so ngau nhien
        public static string GenerateRandomCode()
        {
            // For generating random numbers.
            Random random = new Random();
            string s = "";
            for (int i = 0; i < 4; i++)
                s = String.Concat(s, random.Next(10).ToString());
            return s;
        }

        public static void DeleteFile(string filePath)
        {
            try
            {
                FileInfo TheFile = new FileInfo(PhysicalApplicationPath() + filePath);
                if (TheFile.Exists)
                    TheFile.Delete();
                else
                    throw new FileNotFoundException();
            }
            catch (FileNotFoundException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void UploadFile(FileUpload fileUpload, string fileName, string fileType)
        {
            string url = HttpContext.Current.Request.UrlReferrer.ToString();
            if (fileUpload.HasFile)
            {
                string ext =
                    fileUpload.PostedFile.FileName.Substring(fileUpload.PostedFile.FileName.LastIndexOf(".") + 1);
                try
                {
                    if (ext.ToUpper() == fileType.ToUpper())
                    {
                        if (fileUpload.PostedFile.ContentLength < 1024000)
                        {
                            //Xóa file backup cũ nếu có
                            FileInfo backupFile =
                                new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup");
                            if (backupFile.Exists) backupFile.Delete();
                            //Backup file cũ
                            FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName);
                            if (file.Exists)
                                file.MoveTo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup");
                            //Upload file mới
                            fileUpload.SaveAs(HttpContext.Current.Server.MapPath("~/") + fileName);
                            MessageBox.Show(Constants.UPLOAD_FILE_SUCESS, url);
                            //HttpContext.Current.Server.Transfer(HttpContext.Current.Request.UrlReferrer.ToString());
                        }
                        else MessageBox.Show(Constants.UPLOAD_FILE_LARGER_FAILD, url);
                    }
                    else MessageBox.Show(Constants.UPLOAD_FILE_TYPE_FAILD, url);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Constants.UNKNOW_ERROR, url);
                }
            }
            else
            {
                MessageBox.Show(Constants.NO_FILE_UPLOAD, url);
            }
        }
        public static void RestoreFile(string fileName)
        {
            FileInfo backup1 = new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName);
            FileInfo backup2 = new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup");
            FileInfo backup3 = new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup" + "_temp");
            if (backup2.Exists)
            {
                if (backup1.Exists)
                    backup1.MoveTo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup" + "_temp");
                if (backup2.Exists) backup2.MoveTo(HttpContext.Current.Server.MapPath("~/") + fileName);
                if (backup3.Exists) backup3.MoveTo(HttpContext.Current.Server.MapPath("~/") + fileName + "_backup");
                MessageBox.Show(Constants.RESTORE_SUCCESS, HttpContext.Current.Request.UrlReferrer.ToString());
            }
            else MessageBox.Show(Constants.NO_FILE_BACKUP, HttpContext.Current.Request.UrlReferrer.ToString());
        }

        public static DataSet ConvertListToDataSet<T>(IList<T> list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);

            //add a column to table for each public property on T
            foreach (PropertyInfo propertyInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;

                t.Columns.Add(propertyInfo.Name, ColType);
            }

            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();

                foreach (PropertyInfo propertyInfo in elementType.GetProperties())
                {
                    row[propertyInfo.Name] = propertyInfo.GetValue(item, null) ?? DBNull.Value;
                }

                t.Rows.Add(row);
            }

            return ds;
        }

        public static SqlConnection getConnection()
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["ICELConnection"].ConnectionString);
        }

        public static String strimText(string input, int lenghtOutput)
        {
            int viTriCat = input.Length;
            if (viTriCat < lenghtOutput)
                return input + " ...";
            while ((input[viTriCat - 1] != Char.Parse(" ")) && (input[viTriCat - 1] > 0))
                viTriCat--;
            return input.Substring(0, viTriCat - 1) + " ...";
        }

        public static List<int> genRandomListNumber(int from, int to)
        {
            List<int> list = new List<int>();
            List<int> tempList = new List<int>();

            Random rd = new Random();
            for (int i = from; i <= to; i++) tempList.Add(i);
            int lenght = tempList.Count;
            for (int index = 0; index < lenght; index++)
            {
                int j = rd.Next(tempList.Count);
                list.Add(tempList[j]);
                tempList.RemoveAt(j);
            }

            return list;
        }

        public static int tryParseInt(string i)
        {
            try
            {
                int j = Int32.Parse(i);
                return j;
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }
}
